package com.css.dzj.dzjap.modules.enterprise.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.css.dzj.dzjap.common.util.*;
import com.css.dzj.dzjap.modules.enterprise.dao.EnterpriseJSDao;
import com.css.dzj.dzjap.modules.enterprise.entity.ApEnterpriseCreditEntity;
import com.css.dzj.dzjap.modules.enterprise.entity.QApEnterpriseCreditEntity;
import com.css.dzj.dzjap.modules.enterprise.service.EnterpriseJSService;
import com.css.dzj.dzjap.modules.info.service.ConstrService;
import com.css.dzj.dzjap.sys.user.entity.LoginUser;
import com.querydsl.core.QueryResults;
import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.core.types.Predicate;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class EnterpriseJSServiceImpl implements EnterpriseJSService {
    @Autowired
    private EnterpriseJSDao priseDao;

    @Value("${ZFJG_URL}")
    private String zfjgUrl;


    //注入JPAQueryFactory工厂
    @Autowired
    JPAQueryFactory jpaQueryFactory;


    @Autowired
    ConstrService constrService;

    @Autowired
    HttpServletRequest request;

    @Autowired
    ServiceUtil serviceUtil;
    /**
     * 查询评价单位或建设单位信用信息表
     */
    @Override
    public ApEnterpriseCreditEntity getEnterPrise(String enterpriseCreditId , String enterpriseCredittype) {

        if(StringUtils.isEmpty(enterpriseCreditId) && StringUtils.isEmpty(enterpriseCredittype)){

            throw new RuntimeException("参数为空");
        }
        QApEnterpriseCreditEntity qPrise = QApEnterpriseCreditEntity.apEnterpriseCreditEntity;
        return jpaQueryFactory
                .selectFrom(qPrise)
                .where(  qPrise.enterpriseCreditId.eq(enterpriseCreditId),
                        qPrise.delFlag.eq(Constant.NO_DELETE),
                        qPrise.enterpriseCredittype.eq(enterpriseCredittype),
                        qPrise.excpresState.eq(Constant.EXCPRES_STATE_NO)
                )
                .fetchOne();
    }

    /**
     * 添加评价单位或建设单位信用信息表
     */
    @Override
    @Transactional
    public String addEnterPrise(ApEnterpriseCreditEntity enterPrise) {

        if(!StringUtils.isEmpty(enterPrise) && !StringUtils.isEmpty(enterPrise.getCreditClueReasons())) {
            if("信用分类D".equals(enterPrise.getCreditClueReasons()) || "信用分类E".equals(enterPrise.getCreditClueReasons()) ||
                    "信用分类一次性下降≥2档".equals(enterPrise.getCreditClueReasons()) || "击中特定负面".equals(enterPrise.getCreditClueReasons())){
                String enterpriseVO = JSON.toJSONStringWithDateFormat(enterPrise,"yyyy-MM-dd", SerializerFeature.WriteDateUseDateFormat);
                String result = HttpClientUtil.doPostJson(zfjgUrl + "/clue/enterprisevo",enterpriseVO);
            }
        } else {
            throw new RuntimeException("企业信用信息或信用线索必填字段为空");
        }

        QApEnterpriseCreditEntity qPrise = QApEnterpriseCreditEntity.apEnterpriseCreditEntity;
        ApEnterpriseCreditEntity prise = jpaQueryFactory
                .selectFrom(qPrise)
                .where(qPrise.delFlag.eq(Constant.NO_DELETE),
                        qPrise.enterpriseScoreNumber.eq(enterPrise.getEnterpriseScoreNumber()).or(qPrise.enterpriseIdNumber.eq(enterPrise.getEnterpriseIdNumber()))
                      )
                .fetchOne();
        if (prise!=null){
            throw new RuntimeException("建设单位评分编号或建设单位号码已存在！");
        }
        R r = serviceUtil.getUserInfoByRequest(request);
        if(r.getCode().equals("200")){
            LoginUser userInfo =  (LoginUser)r.get("data");
            enterPrise.setCreateUser(userInfo.getLoginName());
            enterPrise.setOrganName(userInfo.getOrgName());
        }
        enterPrise.setEnterpriseNotice("0");
        enterPrise.setDelFlag(Constant.NO_DELETE);
        enterPrise.setExcpresState(Constant.EXCPRES_STATE_NO);
        enterPrise.setCreateTime(new Date());
        try {
            priseDao.save(enterPrise);
            return enterPrise.getEnterpriseCreditId();

        }catch (Exception e){
            return "0";
        }

    }

    /**
     * 修改评价单位或建设单位信用信息表
     */
    @Override
    @Transactional
    public void update(ApEnterpriseCreditEntity enterPrise) {

    }

    /**
     * 删除评价单位或建设单位信用信息表
     */
    @Override
    @Transactional
    public Boolean deleteEnterPrise(String enterpriseCreditId, String enterpriseCredittype) {

        QApEnterpriseCreditEntity qPrise = QApEnterpriseCreditEntity.apEnterpriseCreditEntity;
        if(StringUtils.isEmpty(enterpriseCreditId)){
            return  false;
        }

        try{
            jpaQueryFactory
                    .update(qPrise)
                    .set(qPrise.delFlag,Constant.DELETE)
                    .where(
                            qPrise.enterpriseCreditId.eq(enterpriseCreditId),
                            qPrise.delFlag.eq(Constant.NO_DELETE),
                            qPrise.excpresState.eq(Constant.EXCPRES_STATE_NO),
                            qPrise.enterpriseCredittype.eq(enterpriseCredittype)
                    )
                    .execute();
            return true;
        }catch (Exception e){
            return false;
        }
    }


    /**
     * 查询评价单位或建设单位信用信息表黑名单
     */
    @Override
    public ApEnterpriseCreditEntity getReEnterPrise(String enterpriseCreditId, String enterpriseCredittype) {
        if(StringUtils.isEmpty(enterpriseCreditId) && StringUtils.isEmpty(enterpriseCredittype)){

            throw new RuntimeException("参数为空");
        }
        QApEnterpriseCreditEntity qPrise = QApEnterpriseCreditEntity.apEnterpriseCreditEntity;
        return jpaQueryFactory
                .selectFrom(qPrise)
                .where(  qPrise.enterpriseCreditId.eq(enterpriseCreditId),
                        qPrise.delFlag.eq(Constant.NO_DELETE),
                        qPrise.enterpriseCredittype.eq(enterpriseCredittype),
                        qPrise.excpresState.eq(Constant.EXCPRES_STATE_Yes)
                )
                .fetchOne();
    }


    /**
     *分页查询所有评价单位或建设单位信用信息表
     */
    @Override
    public QueryResults<ApEnterpriseCreditEntity> getAllEnterPrise(Pageable pageable , String enterpriseCredittype, HttpServletRequest request) {

        QApEnterpriseCreditEntity qPrise = QApEnterpriseCreditEntity.apEnterpriseCreditEntity;
        Predicate predicate = qPrise.isNotNull().or(qPrise.isNull());
        predicate = ("".equals(enterpriseCredittype) || enterpriseCredittype == null) ? predicate : ExpressionUtils.and(predicate, qPrise.enterpriseCredittype.eq(enterpriseCredittype));
        predicate = ExpressionUtils.and(predicate, qPrise.delFlag.eq(Constant.NO_DELETE)) ;
        predicate = ExpressionUtils.and(predicate,qPrise.excpresState.eq(Constant.EXCPRES_STATE_NO));
        String orgName= ServiceUtil.getOrgName(request);
        if(orgName.contains("建设单位")) {
            String unsid = constrService.findUnitCode(ServiceUtil.getLoginName(request));
            if (!StringUtils.isEmpty(unsid)) {
                predicate = ExpressionUtils.and(predicate, qPrise.enterpriseIdNumber.eq(unsid));
            }
        }
        return  jpaQueryFactory
                .selectFrom(qPrise)
                .where(
                        predicate
                )
                .orderBy(qPrise.createTime.desc())
                .offset(pageable.getOffset())   //起始页
                .limit(pageable.getPageSize())  //每页大小
                .fetchResults();
    }

    /**
     *分页查询所有评价单位或建设单位信用信息表黑名单
     */
    @Override
    public QueryResults<ApEnterpriseCreditEntity> getAllReEnterPrise(Pageable pageable, String enterpriseCredittype,HttpServletRequest request) {

        QApEnterpriseCreditEntity qPrise = QApEnterpriseCreditEntity.apEnterpriseCreditEntity;
        Predicate predicate = qPrise.isNotNull().or(qPrise.isNull());
        predicate = ("".equals(enterpriseCredittype) || enterpriseCredittype == null) ? predicate : ExpressionUtils.and(predicate, qPrise.enterpriseCredittype.eq(enterpriseCredittype));
        predicate = ExpressionUtils.and(predicate, qPrise.delFlag.eq(Constant.NO_DELETE)) ;
        predicate = ExpressionUtils.and(predicate,qPrise.excpresState.eq(Constant.EXCPRES_STATE_Yes));
        String orgName= ServiceUtil.getOrgName(request);
        if(orgName.contains("建设单位")) {
            String unsid = constrService.findUnitCode(ServiceUtil.getLoginName(request));
            if (!StringUtils.isEmpty(unsid)) {
                predicate = ExpressionUtils.and(predicate, qPrise.enterpriseIdNumber.eq(unsid));
            }
        }
        return  jpaQueryFactory
                .selectFrom(qPrise)
                .where(
                        predicate
                )
                .orderBy(qPrise.abnormalPutdate.desc())
                .offset(pageable.getOffset())   //起始页
                .limit(pageable.getPageSize())  //每页大小
                .fetchResults();
    }



    /**
     *多条件分页查询所有评价单位或建设单位信用信息表
     */
    @Override
    public QueryResults<ApEnterpriseCreditEntity> getAllConEnterPrise(Pageable pageable, String enterpriseCredittype,String enterpriseName,String enterpriseScoreNumber,String enterpriseIdNumber,String enterpriseScore,String enterpriseClassification,HttpServletRequest request) {

        QApEnterpriseCreditEntity qPrise = QApEnterpriseCreditEntity.apEnterpriseCreditEntity;
        Predicate predicate = qPrise.isNotNull().or(qPrise.isNull());
        predicate = ("".equals(enterpriseCredittype) || enterpriseCredittype == null) ? predicate : ExpressionUtils.and(predicate, qPrise.enterpriseCredittype.eq(enterpriseCredittype));
        predicate = ("".equals(enterpriseName) || enterpriseName == null) ? predicate : ExpressionUtils.and(predicate, qPrise.enterpriseName.like("%"+enterpriseName+"%"));
        predicate = ("".equals(enterpriseScoreNumber) || enterpriseScoreNumber == null) ? predicate : ExpressionUtils.and(predicate, qPrise.enterpriseScoreNumber.like("%"+enterpriseScoreNumber+"%"));
        predicate = ("".equals(enterpriseIdNumber) || enterpriseIdNumber == null) ? predicate : ExpressionUtils.and(predicate, qPrise.enterpriseIdNumber.like("%"+enterpriseIdNumber+"%"));
        predicate = ("".equals(enterpriseScore) || enterpriseScore == null) ? predicate : ExpressionUtils.and(predicate, qPrise.enterpriseScore.eq(enterpriseScore));
        predicate = ("".equals(enterpriseClassification) || enterpriseClassification == null) ? predicate : ExpressionUtils.and(predicate, qPrise.enterpriseClassification.eq(enterpriseClassification));

        predicate = ExpressionUtils.and(predicate, qPrise.delFlag.eq(Constant.NO_DELETE)) ;
        predicate = ExpressionUtils.and(predicate,qPrise.excpresState.eq(Constant.EXCPRES_STATE_NO));
        String orgName= ServiceUtil.getOrgName(request);
        if(orgName.contains("建设单位")) {
            String unsid = constrService.findUnitCode(ServiceUtil.getLoginName(request));
            if (!StringUtils.isEmpty(unsid)) {
                predicate = ExpressionUtils.and(predicate, qPrise.enterpriseIdNumber.eq(unsid));
            }
        }
        return  jpaQueryFactory
                .selectFrom(qPrise)
                .where(
                        predicate
                )
                .orderBy(qPrise.createTime.desc())
                .offset(pageable.getOffset())   //起始页
                .limit(pageable.getPageSize())  //每页大小
                .fetchResults();
    }


    /**
     *多条件分页查询所有评价单位或建设单位信用信息表黑名单
     */
    @Override
    public QueryResults<ApEnterpriseCreditEntity> getAllReConEnterPrise(Pageable pageable, String enterpriseCredittype,String enterpriseName,String enterpriseScoreNumber,String enterpriseIdNumber,String enterpriseScore,String enterpriseClassification,HttpServletRequest request) {

        QApEnterpriseCreditEntity qPrise = QApEnterpriseCreditEntity.apEnterpriseCreditEntity;
        Predicate predicate = qPrise.isNotNull().or(qPrise.isNull());
        predicate = ("".equals(enterpriseCredittype) || enterpriseCredittype == null) ? predicate : ExpressionUtils.and(predicate, qPrise.enterpriseCredittype.eq(enterpriseCredittype));
        predicate = ("".equals(enterpriseName) || enterpriseName == null) ? predicate : ExpressionUtils.and(predicate, qPrise.enterpriseName.like("%"+enterpriseName+"%"));

        predicate = ("".equals(enterpriseScoreNumber) || enterpriseScoreNumber == null) ? predicate : ExpressionUtils.and(predicate, qPrise.enterpriseScoreNumber.like("%"+enterpriseScoreNumber+"%"));
        predicate = ("".equals(enterpriseIdNumber) || enterpriseIdNumber == null) ? predicate : ExpressionUtils.and(predicate, qPrise.enterpriseIdNumber.like("%"+enterpriseIdNumber+"%"));
        predicate = ("".equals(enterpriseScore) || enterpriseScore == null) ? predicate : ExpressionUtils.and(predicate, qPrise.enterpriseScore.eq(enterpriseScore));
        predicate = ("".equals(enterpriseClassification) || enterpriseClassification == null) ? predicate : ExpressionUtils.and(predicate, qPrise.enterpriseClassification.eq(enterpriseClassification));

        predicate = ExpressionUtils.and(predicate, qPrise.delFlag.eq(Constant.NO_DELETE)) ;
        predicate = ExpressionUtils.and(predicate,qPrise.excpresState.eq(Constant.EXCPRES_STATE_Yes));
        String orgName= ServiceUtil.getOrgName(request);
        if(orgName.contains("建设单位")) {
            String unsid = constrService.findUnitCode(ServiceUtil.getLoginName(request));
            if (!StringUtils.isEmpty(unsid)) {
                predicate = ExpressionUtils.and(predicate, qPrise.enterpriseIdNumber.eq(unsid));
            }
        }
        return  jpaQueryFactory
                .selectFrom(qPrise)
                .where(
                        predicate
                )
                .orderBy(qPrise.createTime.desc())
                .offset(pageable.getOffset())   //起始页
                .limit(pageable.getPageSize())  //每页大小
                .fetchResults();
    }

    /**
     * 通过统一信用代码查询评价单位或建设单位信用信息黑名单
     */
    @Override
    public ApEnterpriseCreditEntity getTyReConEnterPrise( String enterpriseCredittype, String enterpriseIdNumber) {
        if( StringUtils.isEmpty(enterpriseCredittype) && StringUtils.isEmpty(enterpriseIdNumber)){

            throw new RuntimeException("参数为空");
        }
        QApEnterpriseCreditEntity qPrise = QApEnterpriseCreditEntity.apEnterpriseCreditEntity;
        return jpaQueryFactory
                .selectFrom(qPrise)
                .where(
                        qPrise.delFlag.eq(Constant.NO_DELETE),
                        qPrise.enterpriseCredittype.eq(enterpriseCredittype),
                        qPrise.enterpriseIdNumber.eq(enterpriseIdNumber),
                        qPrise.excpresState.eq(Constant.EXCPRES_STATE_Yes)
                )
                .orderBy(qPrise.createTime.desc())
                .fetchOne();


    }

    /**
     *添加评价单位或建设单位信用信息黑名单
     */
    @Override
    @Transactional
    public String addReConEnterPrise(ApEnterpriseCreditEntity enterPrise) {

        QApEnterpriseCreditEntity qPrise = QApEnterpriseCreditEntity.apEnterpriseCreditEntity;
        ApEnterpriseCreditEntity prise = jpaQueryFactory
                .selectFrom(qPrise)
                .where(qPrise.delFlag.eq(Constant.NO_DELETE),
                        qPrise.enterpriseScoreNumber.eq(enterPrise.getEnterpriseScoreNumber()).or(qPrise.enterpriseIdNumber.eq(enterPrise.getEnterpriseIdNumber()))
                )
                .fetchOne();
        if (prise!=null){
            throw new RuntimeException("建设单位评分编号或建设单位号码已存在！");
        }

        R r = serviceUtil.getUserInfoByRequest(request);
        if(r.getCode().equals("200")){
            LoginUser userInfo =  (LoginUser)r.get("data");
            enterPrise.setCreateUser(userInfo.getLoginName());
            enterPrise.setOrganName(userInfo.getOrgName());
        }
        enterPrise.setDelFlag(Constant.NO_DELETE);
        enterPrise.setExcpresState(Constant.EXCPRES_STATE_Yes);
        enterPrise.setEnterpriseCreditId(SnowflakeId.getId());
        enterPrise.setCreateTime(new Date());
        enterPrise.setAbnormalPutdate(new Date());
        try {
            priseDao.save(enterPrise);
            return enterPrise.getEnterpriseCreditId();

        }catch (Exception e){
            return "0";
        }
    }

    /**
     *
     * 批量删除
     */
    @Override
    @Transactional
    public void update(List<ApEnterpriseCreditEntity> list) {

    }

    /**
     * 建设单位黑白名单表统一信用代码list
     */
    @Override
    @Transactional
    public List idJsHbNumber() {

        QApEnterpriseCreditEntity qPrise = QApEnterpriseCreditEntity.apEnterpriseCreditEntity;
        Predicate predicate = qPrise.isNotNull().or(qPrise.isNull());
        predicate = ExpressionUtils.and(predicate, qPrise.delFlag.eq(Constant.NO_DELETE)) ;
        predicate = ExpressionUtils.and(predicate,qPrise.enterpriseCredittype.eq("1"));

        List<ApEnterpriseCreditEntity> list =jpaQueryFactory
                .selectFrom(qPrise)
                .where(
                        predicate
                )//每页大小
                .fetch();
        List idJsHbNumberList = new ArrayList();
        for(int i=0;i<list.size();i++){

            idJsHbNumberList.add(list.get(i).getEnterpriseIdNumber());
        }

        return idJsHbNumberList;
    }

    /***
     * 建设单位在白名单中
     * @return
     */
    @Override
    public List idJsNumber() {
        QApEnterpriseCreditEntity qPrise = QApEnterpriseCreditEntity.apEnterpriseCreditEntity;
        Predicate predicate = qPrise.isNotNull().or(qPrise.isNull());
        predicate = ExpressionUtils.and(predicate, qPrise.delFlag.eq(Constant.NO_DELETE));
        predicate = ExpressionUtils.and(predicate,qPrise.enterpriseCredittype.eq("1"));
        predicate = ExpressionUtils.and(predicate,qPrise.excpresState.eq("0"));
        List<ApEnterpriseCreditEntity> list =jpaQueryFactory
                .selectFrom(qPrise)
                .where(
                        predicate
                )//每页大小
                .fetch();
        List idNumberList = new ArrayList();
        for(int i=0;i<list.size();i++){

            idNumberList.add(list.get(i).getEnterpriseIdNumber());
        }

        return idNumberList;
    }
}
